<template>
  <el-collapse-item name="rawMaterial" class="raw-material">
    <div class="top" slot="title">
      <PartitionTitle
        title="生产任务单&原材料信息"
        type="line"
      ></PartitionTitle>
      <el-button
        v-if="['1', '2'].includes(status)"
        type="primary"
        size="mini"
        @click.stop="handleAdd"
        >新增</el-button
      >
    </div>
    <!-- 产品汇总 -->
    <div v-for="(workOrder, i) in workOrderList" :key="i">
      <el-form :model="workOrder" label-width="120px" size="small" disabled>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品名称" prop="itemName">
              <el-input type="text" v-model="workOrder.itemName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际产量" prop="actualQuantity">
              <el-input
                type="text"
                v-model="workOrder.actualQuantity"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="未完成数" prop="unCompleteQuantity">
              <el-input
                type="text"
                v-model="workOrder.unCompleteQuantity"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 物料汇总 -->
    <el-table
      :data="logMaterialList"
      tooltip-effect="dark"
      style="width: 100%"
      border
    >
      <el-table-column label="序号" type="index"></el-table-column>
      <el-table-column label="物料编码" prop="itemNo">
        <template slot-scope="{ row }">
          <!-- onlyprev: 上一班有本班没有的物料，shared上一班与本班都有的物料 -->
          <span
            :class="{
              onlyprev: row.ifExtend == 'Y',
              shared: row.ifExtend == 'N' && !!row.preGroupBlcQty,
            }"
            >{{ row.itemNo }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="物料名称" prop="itemName">
        <template slot-scope="{ row }">
          <span
            :class="{
              onlyprev: row.ifExtend == 'Y',
              shared: row.ifExtend == 'N' && !!row.preGroupBlcQty,
            }"
            >{{ row.orderMaterialDto.itemName }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="单位" prop="itemUnit">
        <template slot-scope="{ row }">
          {{ row.orderMaterialDto.itemUnit }}
        </template>
      </el-table-column>
      <el-table-column label="领料量" prop="ptsPickingQty">
        <template slot-scope="{ row }">
          {{ row.orderMaterialDto.ptsPickingQty }}
        </template>
      </el-table-column>
      <el-table-column label="预计退料量" prop="refundQty">
        <template slot-scope="{ row }">
          <el-input-number
            v-if="status == '2' && row.ifExtend === 'Y'"
            v-model="row.refundQty"
            type="text"
            size="mini"
            :controls="false"
            @change="handleChange"
          ></el-input-number>
          <span v-else>{{ row.refundQty }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用量" prop="theoryConsumeQty">
        <template slot-scope="{ row }">
          {{
            toFix(
              Number(row.orderMaterialDto.theoryConsumeQty || 0) +
                Number(row.orderMaterialDto.actualWastageQty || 0),
              2
            )
          }}
        </template>
      </el-table-column>
      <el-table-column label="损耗量" prop="actualWastageQty">
        <template slot-scope="{ row }">
          {{ row.orderMaterialDto.actualWastageQty }}
        </template>
      </el-table-column>
      <el-table-column
        label="上班结余量"
        prop="preGroupBlcQty"
      ></el-table-column>
      <el-table-column
        label="本班预计结余量"
        prop="currentGroupBlcQty"
      ></el-table-column>
    </el-table>
    <!-- 工单详情列表 -->
    <el-collapse-item name="rawMaterialOrders">
      <div class="order-top" slot="title">
        <el-button type="text">展开工单信息</el-button>
      </div>
      <div
        v-for="(workOrder, i) in workOrderList"
        :key="workOrder.orderId"
        class="item"
      >
        <div class="order-title">
          <span>工单{{ i + 1 }}</span>
          <el-button
            v-if="['1', '2'].includes(status)"
            type="text"
            style="color: #409eff"
            @click="handleDelete(workOrder)"
            >取消确认</el-button
          >
        </div>
        <!-- 生产任务单 -->
        <el-form
          :model="workOrder"
          label-width="120px"
          size="small"
          :disabled="status != '2'"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item
                label="实际开始时间"
                prop="actualStarttime"
                :rules="[
                  {
                    required: true,
                    message: '请选择实际开始时间',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-date-picker
                  v-model="workOrder.actualStarttime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder=""
                  :clearable="false"
                  @change="handleWorkOrderTimeChange(workOrder)"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="实际结束时间"
                prop="actualEndtime"
                :rules="[
                  {
                    required: true,
                    message: '请选择实际结束时间',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-date-picker
                  v-model="workOrder.actualEndtime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder=""
                  :clearable="false"
                  @change="handleWorkOrderTimeChange(workOrder)"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="工单编号" prop="erpOrderNo">
                <el-input
                  type="text"
                  v-model="workOrder.erpOrderNo"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品名称" prop="itemName">
                <el-input
                  type="text"
                  v-model="workOrder.itemName"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单位" prop="itemUnit">
                <el-input
                  type="text"
                  v-model="workOrder.itemUnit"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="计划产量" prop="planQuantity">
                <el-input
                  type="text"
                  v-model="workOrder.planQuantity"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="实际产量"
                prop="actualQuantity"
                :rules="[
                  {
                    required: true,
                    message: '请输入实际产量',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input-number
                  v-model="workOrder.actualQuantity"
                  @change="handleChange"
                  :min="0"
                  :step="1"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="未完成数" prop="unCompleteQuantity">
                <el-input
                  type="text"
                  v-model="workOrder.unCompleteQuantity"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- 原材料 -->
        <el-table
          :data="workOrder.orderMaterialDtos"
          tooltip-effect="dark"
          style="width: 100%"
          border
        >
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column label="物料编码" prop="itemNo"></el-table-column>
          <el-table-column label="物料名称" prop="itemName"></el-table-column>
          <el-table-column label="单位" prop="itemUnit"></el-table-column>
          <el-table-column label="领料量" prop="ptsPickingQty">
            <template slot-scope="{ row }">
              <el-input-number
                v-if="status === '2'"
                v-model="row.ptsPickingQty"
                type="text"
                size="mini"
                :controls="false"
                @change="handleChange"
              ></el-input-number>
              <span v-else>{{ row.ptsPickingQty }}</span>
            </template>
          </el-table-column>
          <el-table-column label="预计退料量" prop="ptsRefundQty">
            <template slot-scope="{ row }">
              <el-input-number
                v-if="status === '2'"
                v-model="row.ptsRefundQty"
                type="text"
                size="mini"
                :controls="false"
                @change="handleChange"
              ></el-input-number>
              <span v-else>{{ row.ptsRefundQty }}</span>
            </template>
          </el-table-column>
          <el-table-column label="使用量" prop="theoryConsumeQty">
            <template slot-scope="{ row }">
              {{
                toFix(
                  Number(row.theoryConsumeQty || 0) +
                    Number(row.actualWastageQty || 0),
                  2
                )
              }}
            </template>
          </el-table-column>
          <el-table-column label="损耗量" prop="actualWastageQty">
            <template slot-scope="{ row }">
              <el-input-number
                v-if="status === '2'"
                v-model="row.actualWastageQty"
                type="text"
                size="mini"
                :min="0"
                :controls="false"
                @change="handleChange"
              ></el-input-number>
              <span v-else>{{ row.actualWastageQty }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="上单结转量"
            prop="preOrderCarryQty"
            width="100"
          ></el-table-column> -->
          <el-table-column
            label="本单结余量"
            prop="currentBalanceQty"
          ></el-table-column>
          <el-table-column label="备注" prop="remark">
            <template slot-scope="{ row }">
              <el-input
                v-if="status === '2'"
                v-model="row.remark"
                type="text"
                size="mini"
              ></el-input>
              <span v-else>{{ row.remark }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-collapse-item>
    <!-- 生产任务单弹框 -->
    <TaskBillDialog
      :visible.sync="dialogVisible"
      :defaultSearch="taskBillDefaultSearch"
      :selectableCallBack="selectableCallBack"
      @submit="handleSave"
    ></TaskBillDialog>
  </el-collapse-item>
</template>
<script>
import TaskBillDialog from "./taskBillDialog";
import { cancelOrder, confirmOrder } from "@/api/workOrder/confirmClose";
import {
  refershGroupOrderQtys,
  getHandoverDetail,
  getActualQtyByOrderIdAndTime,
} from "@/api/shifts/shiftHandover";
import { mapState, mapMutations } from "vuex";
export default {
  components: { TaskBillDialog },
  props: {
    // 表单状态，控制不同情况下 表单呈现的效果，1-接班，2-交班，3-历史查看
    status: {
      type: String,
      default: "1",
    },
  },
  data() {
    return {
      // 物料汇总
      logMaterialList: [],
      // 工单列表
      workOrderList: [],
      // 工单弹框列表
      dialogVisible: false,
      selectableCallBack: (row) => {
        const index = this.workOrderList.findIndex((ele) => ele.id == row.id);
        return index == -1;
      },
    };
  },
  computed: {
    ...mapState({
      handoverDetail: (state) => state.turnOnDuty.handoverDetail,
    }),
    detailsData() {
      return this.handoverDetail;
    },
    taskBillDefaultSearch() {
      if (!this.detailsData) {
        return {};
      }
      return {
        orderStatus: "TO_CONFIRM,TO_CLOSE",
        factoryDeptCode: this.detailsData.factoryDeptCode || null,
        workshopId: this.detailsData.workshopId || null,
        lineId: this.detailsData.lineId || null,
        groupId: this.detailsData.groupId || null,
      };
    },
  },
  mounted() {},
  methods: {
    ...mapMutations("turnOnDuty", [
      "SET_HANDOVER_ORDERDOTS",
      "SET_HANDOVER_LOGMATERIALDOTS",
    ]),
    // 值变更
    handleChange(value) {
      // 没有填写时，不刷新数据
      if (value == undefined) {
        return;
      }
      this.SET_HANDOVER_ORDERDOTS(this.workOrderList);
      this.SET_HANDOVER_LOGMATERIALDOTS(this.logMaterialList);
      // 刷新数据
      this.handleRefershGroupOrderQtys();
    },
    // 刷新数据
    handleRefershGroupOrderQtys() {
      const { produceLogId, preProduceLogId, orderDtos, logMaterialDtos } =
        this.detailsData;
      const param = {
        produceLogId,
        preProduceLogId,
        orderDtos: orderDtos.map((ele) => ({
          id: ele.id,
          planQuantity: ele.planQuantity,
          actualQuantity: ele.actualQuantity,
          orderMaterialDtos:
            ele.orderMaterialDtos?.map((o) => ({
              id: o.id,
              orderId: o.orderId,
              itemNo: o.itemNo,
              planQty: o.planQty,
              ptsPickingQty: o.ptsPickingQty,
              ptsRefundQty: o.ptsRefundQty,
              collectWastageQty: o.collectWastageQty,
              actualWastageQty: o.actualWastageQty,
              theoryConsumeQty: o.theoryConsumeQty,
              currentBalanceQty: o.currentBalanceQty,
            })) || [],
        })),
        logMaterialDtos: logMaterialDtos.map((ele) => ({
          id: ele.id,
          produceLogId: ele.produceLogId,
          itemNo: ele.itemNo,
          ifExtend: ele.ifExtend,
          refundQty: ele.refundQty,
          preGroupBlcQty: ele.preGroupBlcQty,
          currentGroupBlcQty: ele.currentGroupBlcQty,
        })),
      };
      refershGroupOrderQtys(param).then((res) => {
        if (res?.data?.orderDtos) {
          const _orderDtos = this.detailsData.orderDtos;
          this.mergeData(_orderDtos, res.data.orderDtos);
          this.SET_HANDOVER_ORDERDOTS(_orderDtos);
        }
        if (res?.data?.logMaterialDtos) {
          const _logMaterialDtos = this.detailsData.logMaterialDtos;
          this.mergeData(_logMaterialDtos, res.data.logMaterialDtos);
          this.SET_HANDOVER_LOGMATERIALDOTS(_logMaterialDtos);
        }
      });
    },
    // 新增工单
    handleAdd() {
      this.dialogVisible = true;
    },
    // 取消确认工单
    handleDelete(order) {
      this.$confirm(`是否确定取消该工单？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return cancelOrder({ id: order.id });
        })
        .then(() => {
          this.refreshOrders();
        });
    },
    // 确认工单
    handleSave(selectionList) {
      if (!selectionList?.length) {
        return;
      }
      // 查找最大的工单顺序
      let maxOrderSn = 0;
      if (this.workOrderList?.length) {
        maxOrderSn = this.workOrderList.reduce((prev, next) => {
          return prev.orderSn > next.orderSn ? prev.orderSn : next.orderSn;
        }, 0);
      }
      maxOrderSn++;
      const selectitem = {
        ...selectionList[0],
        orderSn: maxOrderSn,
      };
      const parmas = {
        orderSn: selectitem.orderSn,
        id: selectitem.id,
        // actualStarttime: this.detailsData.workStartTime,
      };
      // 生产记录ID在交班场景下需要传，接班场景不需要传
      if (this.status == "2") {
        parmas.groupProduceLogId = this.detailsData.produceLogId;
      }
      confirmOrder(parmas).then((res) => {
        this.refreshOrders();
      });
    },
    refreshOrders() {
      getHandoverDetail(this.detailsData.produceLogId).then((res) => {
        this.SET_HANDOVER_ORDERDOTS(res.data.orderDtos);
        this.SET_HANDOVER_LOGMATERIALDOTS(res.data.logMaterialDtos);
      });
    },
    // 工单的开始/结束时间修改
    handleWorkOrderTimeChange(workOrder) {
      const order = this.workOrderList.find(
        (ele) => ele.orderId == workOrder.orderId
      );
      if (!order) {
        return;
      }
      // 更新实际产量
      const { id, actualStarttime, actualEndtime } = order;
      if (!actualStarttime || !actualEndtime) {
        this.msgWarning("请选择实际开始实际和实际结束时间！");
        return;
      }
      const param = {
        id,
        actualStarttime,
        actualEndtime,
      };
      getActualQtyByOrderIdAndTime(param)
        .then((res) => {
          // res.data=0也不覆盖
          if (res?.data) {
            order.actualQuantity = res.data;
            this.handleChange(res.data);
          }
        })
        .catch(() => {});
    },
  },
  watch: {
    "detailsData.orderDtos": {
      handler(newVal) {
        this.workOrderList = newVal || [];
      },
      immediate: true,
    },
    "detailsData.logMaterialDtos": {
      handler(newVal) {
        this.logMaterialList = newVal || [];
      },
      immediate: true,
    },
  },
};
</script>
<style lang="scss" scoped>
.raw-material {
  ::v-deep .el-table {
    .el-table__header {
      .el-table__cell {
        padding: 0;
      }
    }
    .el-table__body {
      .el-table__cell {
        padding: 5px 0;
      }
    }
  }
  .item:not(:first-child) {
    margin-top: 16px;
  }
}
.top {
  margin: 20px 0 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-right: 16px;
}
.block-title {
  margin-bottom: 0;
}
.header-cell {
  text-align: center;
  .sub-title {
    font-weight: 500;
  }
}
.order-title {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  span:first-child {
    font-size: 15px;
    font-weight: bold;
    color: #409eff;
    &::before {
      content: "";
      display: inline-block;
      width: 7px;
      height: 7px;
      border-radius: 50%;
      vertical-align: middle;
      margin-right: 6px;
      background: #409eff;
    }
  }
}
.el-date-editor.el-input,
.el-input-number {
  width: 100%;
}
.onlyprev {
  color: #f5b335;
}
.shared {
  color: #88c446;
}
</style>
